/**
 * Created by zhangxiaoyu on 16/12/12.
 */
angular.module('hyt.toolsCtrl',[])

  .controller('toolsCtrl',function($scope,Storage){
    var lat=Storage.get('lat');
    var long=Storage.get('long');
    var point = new BMap.Point(long,lat);
    var geoc = new BMap.Geocoder();
    geoc.getLocation(point, function(rs){
      var addComp = rs.addressComponents;
      var city=addComp.city.replace('市','');
      Storage.set('city',city);
    });
  })
  .controller('calculatorCtrl',function(){
    $(".scroll").addClass('fullScreen');
    var oCalc = document.getElementById("calc");
    var aA = oCalc.getElementsByTagName("a");
    var aInput = oCalc.getElementsByTagName("input")[0];
    var oFormula = document.getElementById("formula");
    var s = false;
    var i = 0;

    for (i = 0; i < aA.length; i++){
      aA[i].onfocus = function ()
      {
        this.blur()
      };
      aA[i].onclick = function ()
      {
        switch(this.innerHTML)
        {
          case "c":
            aInput.value =  0;
            oFormula.value = "";
            break;
          case "%":
            count("%");
            break;
          case "÷":
            count("/");
            break;
          case "×":
            count("*");
            break;
          case "-":
            count("-");
            break;
          case "+":
            count("+");
            break;
          case "=":
            s || (oFormula.value += aInput.value);
            aInput.value = eval(oFormula.value.replace(/\%\/\*\-\+/,''));
            aInput.value = aInput.value.substr(0,10).replace("NaN",0);
            s = true;
            break;
          case ".":
            if(aInput.value.search(/[\.\%\/\*\-\+]/) != -1)
              break;
          default:
            s && (aInput.value = 0, oFormula.value = "", s = false);
            aInput.value.length < 10 && (aInput.value = (aInput.value + this.innerHTML).replace(/^[0\%\/\*\-\+](\d)/,"$1"));
        }
      };

      function count(a)
      {

        if(s)
        {
          oFormula.value = aInput.value + a;
          aInput.value = a;
          s = false;
        }
        else
        {
          /[\%\/\*\-\+]$/.test(aInput.value) || (oFormula.value += aInput.value);
          aInput.value = a;
          /[\%\/\*\-\+]$/.test(oFormula.value) || (oFormula.value += aInput.value);
          oFormula.value = oFormula.value.slice(-1) != a ? oFormula.value.replace(/.$/,a) : oFormula.value
        }
      }
    }
  })
  .controller('gpsMapCtrl',function($timeout,Storage,$ionicModal,$scope,$ionicLoading){
    var lat=Storage.get('lat');
    var long=Storage.get('long');
    var map = new BMap.Map("allmap");
    var gpsPoint = new BMap.Point(long, lat);
    $scope.driving ={
      myPosition:'',
      start:'',
      end:''
    };
    map.centerAndZoom(gpsPoint, 15);
    map.addControl(new BMap.NavigationControl());
    $timeout(function(){
      BMap.Convertor.translate(gpsPoint,0,translateCallback);     //真实经纬度转成百度坐标
    },200);
    //坐标转换完之后的回调函数
    translateCallback = function (point){
      map.centerAndZoom(point, 15);
      var myIcon = new BMap.Icon("img/point.png", new BMap.Size(30,41));
      var marker = new BMap.Marker(point,{icon:myIcon});  // 创建标注
      map.addOverlay(marker);// 将标注添加到地图中
      $scope.driving.myPosition=point;
      var geoc = new BMap.Geocoder();

      map.addEventListener("click", function (e) {
        var pt = e.point;
        geoc.getLocation(pt, function (rs) {
          var addComp = rs.addressComponents;
          var opts = {
            width: 200,     // 信息窗口宽度
            height: 60     // 信息窗口高度
          };
          var infoWindow = new BMap.InfoWindow("地址：" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber, opts);  // 创建信息窗口对象
          marker.addEventListener("click", function () {
            map.openInfoWindow(infoWindow, point); //开启信息窗口
          });
        });
      });
    };
    // 线路查询
    $ionicModal.fromTemplateUrl('templates/tab-tool/GPSMap/searchDriving.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });

    $scope.searchDriving=function(){
      if ($scope.driving.end==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入终止地",
          duration: 1500
        });
      }else {
        var routePolicy ="BMAP_DRIVING_POLICY_LEAST_TIME";
        map.clearOverlays();
        if ($scope.driving.start==''){
          search($scope.driving.myPosition,$scope.driving.end,routePolicy);
        }else {
          search($scope.driving.start,$scope.driving.end,routePolicy);
        }
        $scope.modal.hide();
      }
    };
    function search(start,end,route){
      var driving = new BMap.DrivingRoute(map, {renderOptions:{map: map, autoViewport: true},policy: route});
      driving.search(start,end);
    }
  })
  .controller('noteCtrl',function($scope,Storage,NoteService,DeleteNote,$ionicLoading,AddOrUpdateNote,$stateParams,$state){
    var loginMsg=Storage.get('user');
    var param={
      userMsg:{
         username:loginMsg.username,
         password:loginMsg.password,
         uuid:loginMsg.uuid
      }
    };
    var paramDelete={
      id:'',
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    $scope.paramAdd={
      content:$stateParams.content,
      id:$stateParams.id,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    NoteService.getNoteData(param);
    $scope.$on('NoteList.Updated', function() {
      $scope.noteData=NoteService.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      NoteService.getNoteData(param);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      NoteService.getMoreNoteData(param);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return NoteService.hasNextPage();
    };


    $scope.onItemDelete = function(item) {
      paramDelete.id=item.ID;
      DeleteNote.deleteNote(JSON.stringify(paramDelete));
    };

    $scope.$on('DeleteNote.Updated', function() {
      var result=DeleteNote.getResult();
      if(result.success==true){
        $ionicLoading.show({
          noBackdrop: true,
          template: '删除成功',
          duration: 600
        });
        NoteService.getNoteData(param);
      }
    });

    //保存编辑
    $scope.saveNote=function () {
      AddOrUpdateNote.saveNote($scope.paramAdd);
    };

    var newDate=new Date();
    var year=newDate.getFullYear();
    if ((newDate.getMonth()+1).toString().length==1){
      var month='0'+(newDate.getMonth()+1);
    }else {
      var month=newDate.getMonth()+1;
    }
    if ((newDate.getDate()).toString().length==1){
      var date='0'+newDate.getDate();
    }else {
      var date=newDate.getDate();
    }
    $scope.nowDate=year+"-"+month+"-"+date;
    $scope.$on('AddNote.Updated',function () {
      var result=AddOrUpdateNote.getResult();
      if(result.success==true){
        $ionicLoading.show({
          noBackdrop: true,
          template: '保存成功',
          duration: 1500
        });
        NoteService.getNoteData(param);
        $state.go("note");
      }
    })
  })

.controller('weatherCtrl',function($cordovaGeolocation,$timeout,$scope,Storage){
  var lat=Storage.get('lat');
  var long=Storage.get('long');
  $scope.city=Storage.get('city');
  $('#lbs-weather').css('display','none');
  if ($scope.city==''){
    $("#lbs-weather").css('display','none');
    $('#wait').css('display','none');
  }else {
    $("#noFoundGps").css('display','none');
  }
  $scope.$on('$ionicView.enter', function() {
    $timeout(function(){
      $(".weather-list").children("div.tabs").removeClass("tabs").addClass("tabs-weather");
      $(".today_btn").removeClass("tab").addClass("tab-weather");
      $(".week_btn").removeClass("tab").addClass("tab-weather");
      $(".weather").children("div.detail").removeClass("detail");
      $(".pm2_5").children("div.detail").removeClass("detail");
      $(".d1").children("div.left").children("div").css("margin-top","10px");
      $(".d1").children("div.right").children("div.bg1").removeClass("bg").addClass("bg-weather");
      $('#lbs-weather').css('display','inline');
      $('#wait').css('display','none');
    },5000);
  });
})


